package com.hh.core.shiro.check;

import javax.servlet.http.HttpServletRequest;

import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;

import com.hh.core.common.SpringContextHolder;
import com.hh.core.shiro.entity.ShiroUser;
import com.hh.core.shiro.util.ShiroUtil;
import com.hh.core.util.HttpCoreUtil;

@Service
@DependsOn("springContextHolder")
@Transactional(readOnly = true)
public class PermissionCheckFactory implements ICheck {

	public static ICheck me() {
        return SpringContextHolder.getBean(ICheck.class);
    }
	
	@Override
	public boolean check(Object[] permissions) {
		ShiroUser user = ShiroUtil.getUser();
        if (null == user) {
            return false;
        }
        String join = ArrayUtil.join(permissions, ",");
        if (ShiroUtil.hasAnyRoles(join)) {
            return true;
        }
        return false;
	}

	@Override
	public boolean checkAll() {
		HttpServletRequest request = HttpCoreUtil.getRequest();
        ShiroUser user = ShiroUtil.getUser();
        if (null == user) {
            return false;
        }
        //获取当前访问的 url 路径，并去除域名、ip、上下文根
        String requestURI = request.getRequestURI().replace(request.getContextPath(), "");
        /*
         *由于有些链接是/结尾的所以去掉
         * 判断当前链接是否通过/结尾
         */
        if (requestURI.endsWith("/")){
            requestURI=requestURI.substring(0,requestURI.length()-1);
        }
        /*
         * 考虑到部分请求采用 rest 风格，将参数直接写在 url 结尾，此处应用需要对其做出处理
         *
         */
        String[] str = requestURI.split("/");
        StringBuilder sbUrl = new StringBuilder();
        for(String url:str){
            if(StrUtil.isNotBlank(url)&& !NumberUtil.isNumber(url)){
                sbUrl.append("/"+url);
            }
        }

        if (ShiroUtil.hasPermission(sbUrl.toString())) {
            return true;
        }
		return false;
	}

}
